//增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）
package XML作业;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class ZuoYe5 {
	public static void main(String[] args) throws Exception {
		Scanner in = new Scanner(System.in);
		SAXReader reader = new SAXReader();
		while (true) {
			Document doc = reader.read(new File("products.xml"));
			Element root = doc.getRootElement();
			List<Element> list = root.selectNodes("product");
			System.out.println(list.size());
			System.out.println("请输入商品号");
			String num = in.next();
			System.out.println("请输入商品名称");
			String mingcheng = in.next();
			int i = 0;
			for (i = 0; i < list.size(); i++) {
				if (list.get(i).selectSingleNode("itemno").getText().equals(num)) {
					System.out.println("编号重复，请重新输入");
					break;
				}
				if (list.get(i).selectSingleNode("name").getText().equals(mingcheng)) {
					System.out.println("名称重复，请重新输入");
					break;
				}
			}
			if (i < list.size()) {
				continue;
			}
			Element newPro = root.addElement("product");
			newPro.addAttribute("discount", "true");
			newPro.addAttribute("factoryaddr", "上海");
			newPro.addElement("itemno").setText(num);
			newPro.addElement("name").setText(mingcheng);
			newPro.addElement("price").setText("25");
			newPro.addElement("stockcount").setText("36");
			newPro.addElement("unit").setText("盒");

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter xm = new XMLWriter(new FileWriter("products.xml"), format);
			xm.write(doc);
			xm.close();
			System.out.println("是否还需要添加（是/否）？");
			if (in.next().equals("否")) {
				break;
			}
		}
	}
}